/**
 * Created by yoyoyk on 2017/3/18.
 * Dalyn update on 2017/4/13.
 */
import React from "react";
import Relay from "react-relay";
import Confirm from '../../../common/Confirm'
import Select from '../../../common/Select'
import InputBox from '../../../common/InputBox'
import Packapply from './Packapply'
import Handlelog from './Handlelog'
import OrderdetailPartA from './OrderdetailPartA'
import OrderdetailPartB from './OrderdetailPartB'
import Reactkey from "../../../util/ReactKey";
import { Table, Icon, message, Tooltip } from 'antd';
import Util from "../../../util/Util";
import InfoOrderMutation from "../mutation/InfoOrderMutation"
import InfoEnquiryOrderMutation from "../mutation/InfoEnquiryOrderMutation"
import "./css/OrderDetail.css"
import AddImgModal from "./AddImgModal";
import OrderdetailContractInfo from './OrderdetailContractInfo'
// import OrderdetailAcceptButton from './OrderdetailAcceptButton'; //接单按钮

/*信息列表*/
export default class Orderdetail extends React.Component{
    constructor(props){
        super(props);
        this.state={
            num:0,
            width:0,
            orderGoodss:[],
            order:[],
            deliverRequests: [],
            isLoading: true
        };
        this.orderpartA = "";
        this.orderpartB = "";
        this.enterpriseId = sessionStorage.getItem('enterpriseId');
        this.serviceType = sessionStorage.getItem('serviceType');

        this.money={
            total:87887,pay:6786
        }
    }
    componentWillMount(){
        if(this.props.enquiryId !='' && this.props.enquiryId != undefined) {
            this.EnquiryOrderdetail();
        } else {
            this.Orderdetail();
        }
    }

    showOrderdetail(){
        if(this.props.enquiryId !='' && this.props.enquiryId != undefined) {
            this.EnquiryOrderdetail();
        } else {
            this.Orderdetail();
        }
    }

    EnquiryOrderdetail(){
        this.state.width=this.money.pay/this.money.total*460
        /*infoorder接口*/
        let oid = this.props.orderId
        Relay.Store.commitUpdate(
            new InfoEnquiryOrderMutation({
                orderId: oid,
                enId: this.enterpriseId,
                enquiryId: this.props.enquiryId
            }),
            {
                onFailure: () => {
                    message.info('请求失败')
                    this.setState({
                        isLoading: false
                    })
                },
                onSuccess: (response) => {
                    let errorCode = response.infoEnquiryOrder.infoEnquiryOrder.errorCode;
                    if(errorCode=='0'){
                        let order = response.infoEnquiryOrder.infoEnquiryOrder.order;
                        let deliverRequests = response.infoEnquiryOrder.infoEnquiryOrder.order.deliverRequests;
                        let orderGoodss = response.infoEnquiryOrder.infoEnquiryOrder.order.orderGoodss;
                        orderGoodss.push({gid: 'key1'},{gid: 'key2'})
                        if (orderGoodss) {
                            orderGoodss.map((o,m) => {
                                if (o.quantity && o.price) {
                                    o.tableOrderMoney = (o.quantity*o.price).toFixed(2)
                                }
                                return o
                            })
                        }
                        this.orderpartA = order.partA;
                        deliverRequests.map((v, i)=> {
                            v.deliverDate = Util.dateFormat(v.deliverDate)   //时间戳转换
                            return v
                        })
                        this.setState({
                            order:order,
                            orderGoodss:order.orderGoodss,
                            deliverRequests: deliverRequests,
                            isLoading: false
                        },()=>{
                            if(this.refs.ordercinfo){
                                this.refs.ordercinfo.setState({
                                    supplyContractsData : order.supplyContracts
                                });
                            }
                        });
                        this.props.orderDetail()
                    } else {
                        message.info('请求失败')
                    }
                }
            }
        )
    }

    Orderdetail(){
      this.state.width=this.money.pay/this.money.total*460
      /*infoorder接口*/
      let oid = this.props.orderId
      Relay.Store.commitUpdate(
          new InfoOrderMutation({
              orderId: oid,
              enId: this.enterpriseId,
          }),
          {
              onFailure: () => {
                  message.info('请求失败')
                  this.setState({
                    isLoading: false
                  })
              },
              onSuccess: (response) => {
                  let errorCode = response.infoOrder.infoOrder.errorCode;
                  if(errorCode=='0'){
                    let order = response.infoOrder.infoOrder.order;
                    let deliverRequests = response.infoOrder.infoOrder.order.deliverRequests;
                    let orderGoodss = response.infoOrder.infoOrder.order.orderGoodss;
                    orderGoodss.push({gid: 'key1'},{gid: 'key2'})
                    if (orderGoodss) {
                      orderGoodss.map((o,m) => {
                        if (o.quantity && o.price) {
                          o.tableOrderMoney = (o.quantity*o.price).toFixed(2)
                        }
                        return o
                      })
                    }
                    this.orderpartA = order.partA;
                    deliverRequests.map((v, i)=> {
                      v.deliverDate = Util.dateFormat(v.deliverDate)   //时间戳转换
                      return v
                    })
                    this.setState({
                        order:order,
                        orderGoodss:order.orderGoodss,
                        deliverRequests: deliverRequests,
                        isLoading: false
                    },()=>{
                      if(this.refs.ordercinfo){
                        this.refs.ordercinfo.setState({
                          supplyContractsData : order.supplyContracts
                        });
                      }
                    });
                    this.props.orderDetail()
                  } else {
                    message.info('请求失败')
                  }
              }
          }
      )
    }

    showImg(url){
        this.refs.addimg.setState({
            url:url,
            visible:true
        });
    }

    sumMoney() {   //合计  大小写
      let sumMoney = 0
      this.state.order.orderGoodss ? this.state.order.orderGoodss.map((v, i) => {
        if (v.quantity && v.price) {
          // sumMoney += (v.quantity*v.price)
          sumMoney += Number(v.tableOrderMoney)
        }
        return sumMoney
      }) : null
      return parseFloat(sumMoney).toFixed(2);
    }

    sumTotal() {
      let sumTotal = 0
      this.state.order.orderGoodss ? this.state.order.orderGoodss.map((v, i) => {
        if (v.quantity) {
          sumTotal += parseFloat(v.quantity)
        }
        return sumTotal
      }) : null
      return sumTotal.toFixed(3)
    }

    /*合同附件*/
    apply(){
        let contractUrl = [];
        let contractUrlSum = []
        if(this.state.order.contractUrl1){
            contractUrl.push(Util.signedContractStr(this.state.order.contractUrl1))
            contractUrlSum.push(this.state.order.contractUrl1)
        }
        if(this.state.order.contractUrl2){
            contractUrl.push(Util.signedContractStr(this.state.order.contractUrl2))
            contractUrlSum.push(this.state.order.contractUrl2)
        }
        if(this.state.order.contractUrl3){
            contractUrl.push(Util.signedContractStr(this.state.order.contractUrl3))
            contractUrlSum.push(this.state.order.contractUrl3)
        }
        if(this.state.order.contractUrl4){
            contractUrl.push(Util.signedContractStr(this.state.order.contractUrl4))
            contractUrlSum.push(this.state.order.contractUrl4)
        }
        if(this.state.order.contractUrl5){
            contractUrl.push(Util.signedContractStr(this.state.order.contractUrl5))
            contractUrlSum.push(this.state.order.contractUrl5)
        }

        this.arr2 = contractUrl ? contractUrl : [];
        return this.arr2.map((item2,index)=>{
            return(
                <Packapply oArr={item2} item2={item2} contractUrlSum={contractUrlSum[index]}/>
            )
        })
    }

    opratelog(){
        this.refs.Handlelog.setState({
            visible : true
        })
    }

    render() {
      const columns = [
        {
          title: '交货时间',
          dataIndex: 'deliverDate',
          key: 'deliverDate',
        },
        {
          title: '数量',
          dataIndex: 'amount',
          key: 'amount',
        },
        {
          title: '备注',
          dataIndex: 'remark',
          key: 'remark',
        }
      ];
      const columnsGoodsDetail = [
        {
          title: '款号',
          dataIndex: 'styleNo',
          key: 'styleNo',
        },
        {
          title: '品名',
          dataIndex: 'productName',
          key: 'productName',
          width: 200,
          render: ((text, record, index)=>{
            if(index == this.state.order.orderGoodss.length-2) {
              return '合计'
            } else if(index == this.state.order.orderGoodss.length-1) {
              return '合计(大写)'
            } else {
              return record.productName
            }
          })
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description',
          width: 200,
          render: ((text, record, index)=>{
            const obj = {
              children: text,
              props: {},
            };
            if(index == this.state.order.orderGoodss.length-1) {
              obj.children = Util.numtoChinese(this.sumMoney())
              obj.props.colSpan  = 5;
              return obj
            } else if(index == this.state.order.orderGoodss.length-2) {
              obj.props.colSpan  = 6;
              return obj;
            } else {
              return record.description
            }
          })
        },
        {
          title: '颜色',
          dataIndex: 'colour',
          key: 'colour',
          width: 100,
          render: ((text, record, index)=>{
            const obj = {
              children: text,
              props: {},
            };
            if(index == this.state.order.orderGoodss.length-1) {
              obj.props.rowSpan = 0
              return obj
            } else if(index == this.state.order.orderGoodss.length-2) {
              return this.sumTotal()
            } else {
              return record.colour
            }
          })
        },
        {
          title: '花型图片',
          dataIndex: 'url',
          key: 'url',
          width: 100,
          render: ((text, record, index)=>{
            const obj = {
              children: text,
              props: {},
            };
            if(index == this.state.order.orderGoodss.length-1) {
              obj.props.colSpan = 0
              return obj
            } else if(index == this.state.order.orderGoodss.length-2) {
              return this.sumMoney()
            } else if(record.url){
              return (<img src={record.url} style={{width:140,height:33}} alt="" onClick={this.showImg.bind(this, record.url)}/>)
            }
          })
        },
        {
          title: '规格',
          dataIndex: 'specification',
          key: 'specification',
          width: 100,
          render: ((text, record, index) => {
            if (index < this.state.order.orderGoodss.length-2) {
              return record.specification
            }
          })
        },
        {
          title: '单位',
          dataIndex: 'prickle',
          key: 'prickle',
          width: 100,
          render: ((text, record, index)=>{
            const obj = {
              children: text,
              props: {},
            };
            if(index == this.state.order.orderGoodss.length-1) {
              obj.props.colSpan = 0
              return obj
            } else if(index == this.state.order.orderGoodss.length-2) {
              obj.props.colSpan = 0
              return obj
            } else {
              return record.prickle
            }
          })
        },
        {
          title: '单价',
          dataIndex: 'price',
          key: 'price',
          width: 100,
          render: ((text, record, index)=>{
            const obj = {
              children: text,
              props: {},
            };
            if(index == this.state.order.orderGoodss.length-1) {
              obj.props.colSpan = 0
              return obj
            } else if(index == this.state.order.orderGoodss.length-2) {
              obj.props.rowSpan = 0
              return obj
            } else {
              return record.price
            }
          })
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          key: 'quantity',
          width: 100,
          render: ((text, record, index)=>{
            const obj = {
              children: text,
              props: {},
            };
            if(index == this.state.order.orderGoodss.length-1) {
              obj.children = ''
              return obj
            } else if(index == this.state.order.orderGoodss.length-2) {
              obj.props.rowSpan = 0
              return obj
            } else {
              return parseFloat(record.quantity).toFixed(3)
            }
          })
        },
        {
          title: '金额',
          dataIndex: 'tableOrderMoney',
          key: 'tableOrderMoney',
          width: 100,
          render: ((text, record, index)=>{
            const obj = {
              children: text,
              props: {},
            };
            if(index == this.state.order.orderGoodss.length-2) {
              obj.props.rowSpan = 0
              return obj
            } else {
              return record.tableOrderMoney
            }
          })
        },
        {
          title: '备注',
          dataIndex: 'desp',
          key: 'desp',
          width: 100,
          render: ((text, record, index)=>{
            const obj = {
              children: text,
              props: {},
            };
            if(index == this.state.order.orderGoodss.length-2) {
              obj.props.colSpan = 0
              return obj
            } else {
                return text && text.length > 5 ? (
                  <Tooltip placement="topLeft" title={text}>
                      <span className='order_detail_remark'>{text}</span>
                  </Tooltip>
                ) : <span>{text}</span> 
            }
          })
        }
      ]
      return (
          <div className="orderdetail_box_style">
            {
              this.state.isLoading ?
                <div style={{background:'#fff',position: 'absolute',height: '100%',zIndex: '3'}}><Icon style={{left: '55%',position: 'fixed',top: '45%',fontSize: '24px'}} type="loading" /></div>
              : (

                <div className='orderdetail_box_style_contract'>
                  {/*合同信息*/}
                  {
                    // this.state.order && this.state.order.status >= 3 ? (
                    //   <OrderdetailContractInfo order={this.state.order} Orderdetail={this.Orderdetail.bind(this)} ref={'ordercinfo'}/>
                    // ) : null
                  }
                  {
                    // <p className="order_detail_title">
                    //     <i className="order_detail_tLine"></i>
                    //     <span className="order_detail_tText">订单详情</span>
                    // </p>
                  }
                    {
                        this.enterpriseId == this.orderpartA ?
                            <OrderdetailPartA Orderdetail={this.Orderdetail.bind(this)} order={this.state.order} serviceType={this.serviceType}  key={Reactkey.key}/>
                            :
                            <OrderdetailPartB Orderdetail={this.Orderdetail.bind(this)} oid={this.props.orderId} ref={'partb'} order={this.state.order} key={Reactkey.key}/>
                    }
                    {/*商品&服务明细*/}
                    <div style={{width: 1150, minHeight: 280}}>
                      <br/>
                      <Table
                        dataSource={this.state.order.orderGoodss}
                        rowKey={record => record.gid}
                        columns={columnsGoodsDetail}
                        className="columnsGoodsDetail"
                        bordered
                        scroll={{ x: 1150 }}
                        pagination={false}
                        title={() => '商品明细'}
                      />
                      { /*交货要求*/  }
                      <Table
                        dataSource={this.state.deliverRequests}
                        rowKey={record => record.did}
                        columns={columns}
                        className="requireTable"
                        bordered
                        pagination={false}
                        title={() => '交货要求'}
                      />

                      {/*备注*/}
                      <div className="order_detail_orderId_bz">
                          <p className="order_detail_addpart_orderp" style={{borderBottom: '1px solid #f0f0f0'}}>备注</p>
                          <div className="order_detail_customer_info clear">
                            <p style={{width:50,height:30,float:'left',lineheight:"30px",fontSize:'14px', color: '#333'}}>备注:</p>
                            <p style={{float:'left',width:'950px'}}>{this.state.order.rmark}</p>
                            <br style={{clear: 'both'}} />
                            <p style={{width:50,height:30,float:'left',lineheight:"30px",fontSize:'14px', color: '#333'}}>附件:</p>
                            <p style={{float:'left',width:'950px'}}>
                              {
                                this.apply()
                              }
                            </p>
                          </div>
                      </div>
                    </div>
                    {
                      this.state.order.partA != this.enterpriseId && (this.state.order.status == 1 || this.state.order.status == 2) ? (
                        <OrderdetailAcceptButton Orderdetail={this.showOrderdetail.bind(this)} order={this.state.order} />
                      ): null
                    }
                </div>
              )
            }
            <AddImgModal ref="addimg" disn={'true'}/>
          </div>
      )
    }
}
